"""
模拟器独立存储管理
所有模拟器配置存储在 config/simulators.json 中，与原始配置文件完全分离
"""
import json
import os
from typing import List, Dict, Any, Optional
from threading import Lock

# 存储文件路径
STORAGE_PATH = './config/simulators.json'

# 线程锁，保证并发安全
_storage_lock = Lock()


def _ensure_storage_file():
    """确保存储文件存在"""
    if not os.path.exists(STORAGE_PATH):
        os.makedirs(os.path.dirname(STORAGE_PATH), exist_ok=True)
        with open(STORAGE_PATH, 'w', encoding='utf-8') as f:
            json.dump({}, f, ensure_ascii=False, indent=2)


def _load_storage() -> Dict[str, Any]:
    """加载整个存储文件"""
    _ensure_storage_file()
    try:
        with open(STORAGE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception:
        return {}


def _save_storage(data: Dict[str, Any]):
    """保存整个存储文件"""
    _ensure_storage_file()
    with open(STORAGE_PATH, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def load_simulators(profile: str, cmd_id: str) -> List[Dict[str, Any]]:
    """
    加载指定版本和指令的模拟器配置

    Args:
        profile: 版本标识，如 "sichuan/2025"
        cmd_id: 指令ID，如 "0x0200"

    Returns:
        模拟器配置列表
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage:
            return []

        if cmd_id not in storage[profile]:
            return []

        return storage[profile][cmd_id]


def save_simulators(profile: str, cmd_id: str, simulators: List[Dict[str, Any]]):
    """
    保存指定版本和指令的模拟器配置

    Args:
        profile: 版本标识
        cmd_id: 指令ID
        simulators: 模拟器配置列表
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage:
            storage[profile] = {}

        storage[profile][cmd_id] = simulators

        _save_storage(storage)


def add_simulator(profile: str, cmd_id: str, simulator: Dict[str, Any]):
    """
    添加模拟器

    Args:
        profile: 版本标识
        cmd_id: 指令ID
        simulator: 模拟器配置
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage:
            storage[profile] = {}

        if cmd_id not in storage[profile]:
            storage[profile][cmd_id] = []

        storage[profile][cmd_id].append(simulator)

        _save_storage(storage)


def update_simulator(profile: str, cmd_id: str, index: int, simulator: Dict[str, Any]) -> bool:
    """
    更新模拟器

    Args:
        profile: 版本标识
        cmd_id: 指令ID
        index: 模拟器索引
        simulator: 新的模拟器配置

    Returns:
        是否更新成功
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage or cmd_id not in storage[profile]:
            return False

        simulators = storage[profile][cmd_id]

        if index < 0 or index >= len(simulators):
            return False

        simulators[index] = simulator

        _save_storage(storage)
        return True


def delete_simulator(profile: str, cmd_id: str, index: int) -> bool:
    """
    删除模拟器

    Args:
        profile: 版本标识
        cmd_id: 指令ID
        index: 模拟器索引

    Returns:
        是否删除成功
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage or cmd_id not in storage[profile]:
            return False

        simulators = storage[profile][cmd_id]

        if index < 0 or index >= len(simulators):
            return False

        del simulators[index]

        _save_storage(storage)
        return True


def update_simulator_enable(profile: str, cmd_id: str, index: int, enable: bool) -> bool:
    """
    更新模拟器启用状态

    Args:
        profile: 版本标识
        cmd_id: 指令ID
        index: 模拟器索引
        enable: 启用状态

    Returns:
        是否更新成功
    """
    with _storage_lock:
        storage = _load_storage()

        if profile not in storage or cmd_id not in storage[profile]:
            return False

        simulators = storage[profile][cmd_id]

        if index < 0 or index >= len(simulators):
            return False

        simulators[index]['enable'] = enable

        _save_storage(storage)
        return True
